<template>
  <div class="main">
    <div style="position: relative;height: 1vh;"></div>
    <div style="position: relative;height: 5vh;width: 97%;
        margin-left: 1.8%;box-shadow: 0px 0px 1px 1PX rgb(242, 240, 240);
        display: flex;align-items: center;">
      <el-button v-for="(item, index) in buttonMenu" v-if="String(item.menuType) == '1'" :key="index" plain type="primary"
        :icon="item.menuicon" @click="e_function_all(item.menuperms, item.menuRouter)">
        {{ item.menuName }}
      </el-button>
    </div>

    <div style="position: relative;height: 1vh;"></div>
    <div
      style="position: relative;height: 6vh;box-shadow: 0px 0px 1px 1PX rgb(242, 240, 240);display: flex;align-items: center;margin-left: 1.8%;width: 97%;">
      部队名字 &nbsp;<el-input placeholder="请输入内容" prefix-icon="el-icon-search" v-model="selectName" clearable
        style="width: 10vw;">&nbsp;</el-input>&nbsp;
      <el-button icon="el-icon-search" plain type="primary" @click="SerchMore">查询</el-button>

    </div>

    <div style="position: relative;height: 1vh;"></div>
    <div style="position: relative;width: 100%;
        margin-left: 1.8%;box-shadow: 0px 0px 1px 1PX rgb(242, 240, 240);
        display: flex;align-items:flex-start;height: 75vh;overflow-y: scroll;">



      <el-tree ref="tree" :load="loadNode" node-key="army_id" lazy :props="defaultProps" accordion
        @node-collapse="handleNodeCollapse" @node-expand="handleNodeClose" :expand-on-click-node="false" :key="treekeyx">
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <div style="display: flex;overflow: hidden; ">
            <div style="width: 40vw;">{{ node.label }}</div>
            <!-- <span>创建时间 : </span>
            <div style="width: 1vw;"></div>
            <div style="width: 11.8vw">{{ data.create_time }}</div>
            <div style="width: 1vw;"></div>
            <span>修改时间 : </span>
            <div style="width: 1vw;"></div>
            <div style="width: 11.8vw">{{ data.update_time }}</div> -->
            <div style="width: 1.8vw;"></div>
            <span>
              <el-button v-for="(item, index) in buttonMenu" v-if="String(item.menuType) == '3'" :key="index" type="text"
                :icon="item.menuicon" @click="e_function_all(item.menuperms, data, node)" size="mini">
                {{ item.menuName }}
              </el-button>
            </span>
          </div>
        </span>
      </el-tree>



    </div>




    <el-dialog title="编辑" :visible.sync="dialogFormVisible">
      <el-form label-width="80px" :rules="rules" :model="pojo" ref="pojo">
        <el-form-item label="军队名称" prop="army_name">
          <el-input v-model="pojo.army_name" />
        </el-form-item>
        <el-form-item label="显示顺序">
          <el-input-number v-model="pojo.order_id" controls-position="right" :min="0" :max="10"></el-input-number>
        </el-form-item>
        <el-button type="primary" @click="handleSave('pojo')">保存</el-button>
        <el-button @click="dialogFormVisible = false">关闭</el-button>
      </el-form>
    </el-dialog>
  </div>
</template>
  
<script>
import ArmyxApi from "@/api/ArmyxRequest"

export default {
  // 组件名称
  name: 'teamxz',
  // 组件参数 接收来自父组件的数据
  props: {},
  // 局部注册的组件
  components: {},
  // 组件状态值
  data() {
    return {
      list: [],
      searchMap: {
        army_id: null,
        army_father_id: 0,
        army_big_father: null,
        army_name: null,
        order_id: null,
        create_time: null,
        update_time: null,
        army_nameLike: null,
      },
      selectName: '',
      pojo: {
        army_id: null,
        army_father_id: null,
        army_big_father: null,
        army_name: '',
        map_id: null,
        order_id: null,
        create_time: null,
        update_time: null,
      },
      dialogFormVisible: false,
      dialogFormVisibleTwo: false,
      childadd: false,
      id: '',
      //表单的验证
      rules: {
        army_name: [
          { required: true, message: '请输入军队名字', trigger: 'change' }
        ],
      },
      //树节点展示
      defaultProps: {
        children: 'armyxTreexes',
        label: 'army_name',
        isLeaf: 'isarmyxchild',
      },
      //修改的节点暂存区
      nodeCheck: {},
      //修改重复节点
      nodereslove: {},
      //刷新树
      treekeyx: 0,
    }
  },
  // 计算属性
  computed: {
    //获取vuex的数据
    buttonMenu() {
      return this.$store.getters['operation/getButtonList'];
    },
  },
  // 侦听器
  watch: {

  },
  // 组件方法
  methods: {
    //动态按钮执行方法
    e_function_all(function_name, function_data, node) {
      this.nodeCheck = node;
      //添加菜单或者目录
      if (function_name == 'addfatherbutton') {
        this.handleEdit('');
      }
      if (function_name == 'addChildren') {
        this.pojo.army_father_id = function_data.army_id;
        if (function_data.army_big_father == 0) {
          this.pojo.army_big_father = function_data.army_id;
        } else {
          this.pojo.army_big_father = function_data.army_big_father;
        }
        this.pojo.army_id = null;
        this.handleEdit('1');
      }
      if (function_name == 'updatearmy') {
        this.handleEdit(function_data.army_id);
      }
      if (function_name === 'deletearmy') {
        if (node.isLeaf === false) {
          this.$message({
            type: 'error',
            message: '底下还有队伍无法删除!'
          });
          return;
        } else {
          this.handleDelete(function_data.army_id);
        }
      }
    },
    fetchData() {

      //编写一个方法请求后端的接口，把返回的数据赋值list
      ArmyxApi.selectListAllArmy(this.searchMap).then(response => {
        //  //把返回的结果赋值模型
        this.list = response.data;
      })

    },
    //清空this.selectMap
    flushSelectMap() {
      this.searchMap = {
        army_id: null,
        army_father_id: 0,
        army_big_father: null,
        army_name: '',
        order_id: null,
        create_time: null,
        update_time: null,
      };
    },
    //将this.lazyindex重新赋予对象
    flushlazyindex() {
      let obj = {
        army_father_id: 0,
        armyx: null,
      };
      this.lazeindex = obj;
    },
    //新增和修改使用同一个函数打开弹窗，区别是新增没有id

    handleEdit(id) {
      if (id === '1') {
        this.id = '';
        this.pojo.army_name = '';
        this.dialogFormVisible = true;
        return;
      }
      this.id = id
      //打开弹窗
      this.dialogFormVisible = true

      if (id !== '') {
        //根据id查询数据绑定到模型上面
        ArmyxApi.selectByArmy_id(id).then(reponse => {
          this.pojo = reponse.data;
        })
      } else {
        this.pojo = {
          army_id: null,
          army_father_id: 0,
          army_big_father: 0,
          army_name: '',
          map_id: null,
          order_id: null,
          create_time: null,
          update_time: null,
        } //清空数据
      }
    },
    //新增和修改保存数据的方法
    handleSave(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.id === null || this.id === '') {
            ArmyxApi.insert(this.pojo).then(reponse => {
              this.addReload(this.nodeCheck, reponse.data);
              this.dialogFormVisible = false;
            })
          } else {
            ArmyxApi.insertOrUpdate(this.pojo).then(reponse => {
              this.editReload(this.nodeCheck, this.pojo);
              //关闭弹窗
              this.dialogFormVisible = false;

            })
          }

        } else {
          this.$message({
            message: '请输入数值',
            type: 'error'
          })
          return false;
        }

      })
    },
    //删除
    handleDelete(id) {
      this.$confirm('您确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        ArmyxApi.deleteByArmy_id(id).then(reponse => {

          this.deleteReload(this.nodeCheck);
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //数组是否有子节点
    listIsChild(demoList) {
      demoList.forEach((elem, index) => {
        if (elem.armyxTreexes.length > 0) {
          demoList[index].isarmyxchild = false;
          demoList[index].armyxTreexes = [];
        } else {
          demoList[index].isarmyxchild = true;
        }
      });
      return demoList;
    },
    //懒加载
    loadNode(node, resolve) {
      this.nodereslove = resolve;
      let valuex = node.data;
      if (node.level === 0) {
        this.searchMap.army_big_father = 0;
        ArmyxApi.selectListAllArmy(this.searchMap).then(response => {
          let listk = this.listIsChild(response.data);
          this.flushSelectMap();
          return resolve(listk);
        })
      } else {
        this.searchMap.army_father_id = valuex.army_id;
        // if (String(valuex.army_big_father) == '0') {
        //   this.searchMap.army_big_father = valuex.army_id;
        // } else {
        //   this.searchMap.army_big_father = valuex.army_big_father;
        // }
        ArmyxApi.selectListAllArmy(this.searchMap).then(response => {
          let listk = this.listIsChild(response.data);
          return resolve(listk);
          this.flushSelectMap();
        })
      }
    },
    //条件查询
    SerchMore() {
      if (this.selectName === '') {
        this.searchMap.army_nameLike = null;
      } else {
        this.searchMap.army_nameLike = this.selectName;
        this.searchMap.army_father_id = null;
        this.searchMap.army_big_father = null;
      }

      this.treekeyx++;
    },
    //节点关闭的钩子,决绝懒加载只加载一次
    handleNodeCollapse(data, node) {
      node.loaded = false
      node.childNodes.splice(0, node.childNodes.length);

    },
    //节点打开的钩子
    handleNodeClose(data, node) {

    },
    //修改成功后执行刷新方法
    editReload(node, data) {
      //将修改成功的数据，赋值给当前操作的node.data,数据驱动，页面就会变成修改后的内容
      Object.keys(data).forEach(key => { node.data[key] = data[key] })
    },
    //添加成功后的方法
    addReload(node, data) {
      //新添加的数据是没有叶子节点的
      data.armyxTreexes = [];

      //如果是父节点

      if (data.army_big_father === 0) {
        data.isarmyxchild = false;
        this.$refs.tree.append(data, null);
        return;
      } else {
        if (node.loaded === true || node.childNodes.length <= 0) {
          data.isarmyxchild = false;   //控制小标
          node.expanded = true; //子节点已经load过，添加后也需要展开子节点，expanded控制展开
          node.loaded = true; //设置父节点已打开
          node.isLeaf = false; //设置父节点不为叶子节点
          this.$refs.tree.append(data, node);//将新添加数据插入到node中，作为其子节点，append为插件提供的方法，需要通过this.$refs.tree调用
          node.data.isarmyxchild = false; //添加了节点之后，此节点不可能是叶子结点了，设置为false，控制前面那个小三角是否显示
          node.childNodes.forEach(item => {
            if (item.data.army_id === data.army_id) {  //deptId是数据的唯一标识，根据返回数据而定，相当于id
              item.isLeaf = true;
            }
          });
        }
      }

    },
    //删除的方法
    deleteReload(node) {
      // let father_node = this.$refs.tree.getNode(data)
      const parent = node.parent;
      this.$refs.tree.remove(node);
      if (parent.childNodes.length == 0) { //判断删除的是否是最后一个节点，如果是，父级节点将变成叶子结点
        parent.isLeaf = true;     //设置叶子节点，用于层级显示
        parent.data.isarmyxchild = true;//设置叶子节点，用于render-content渲染dom
        parent.data.childNodes = [];
      }
      this.$message({
        type: 'success',
        message: '删除成功!'
      });
      // node.loaded = false; //设置父节点已关闭
      // node.childNodes = [];
      // this.loadNode(node, this.nodereslove);
    },

  },
  // 以下是生命周期钩子   注：没用到的钩子请自行删除
  /**
  * 在实例初始化之后，组件属性计算之前，如data属性等
  */
  beforeCreate() {
  },
  /**
  * 组件实例创建完成，属性已绑定，但DOM还未生成，$ el属性还不存在
  */
  created() {
    //在创建vue实例后触发初始化钩子函数
    this.fetchData();
  },
  /**
  * 在挂载开始之前被调用：相关的 render 函数首次被调用。
  */
  beforeMount() {

  },
  /**
  * el 被新创建的 vm.$ el 替换，并挂载到实例上去之后调用该钩子。
  * 如果 root 实例挂载了一个文档内元素，当 mounted 被调用时 vm.$ el 也在文档内。
  */
  mounted() {
  },
  /**
  * 数据更新时调用，发生在虚拟 DOM 重新渲染和打补丁之前。
  * 你可以在这个钩子中进一步地更改状态，这不会触发附加的重渲染过程。
  */
  beforeUpdate() {
  },
  /**
  * 由于数据更改导致的虚拟 DOM 重新渲染和打补丁，在这之后会调用该钩子。
  * 当这个钩子被调用时，组件 DOM 已经更新，所以你现在可以执行依赖于 DOM 的操作。
  */
  updated() {
  },
  /**
  * keep-alive 组件激活时调用。 仅针对keep-alive 组件有效
  */
  activated() {
  },
  /**
  * keep-alive 组件停用时调用。 仅针对keep-alive 组件有效
  */
  deactivated() {
  },
  /**
  * 实例销毁之前调用。在这一步，实例仍然完全可用。
  */
  beforeDestroy() {
  },
  /**
  * Vue 实例销毁后调用。调用后，Vue 实例指示的所有东西都会解绑定，
  * 所有的事件监听器会被移除，所有的子实例也会被销毁。
  */
  destroyed() {
  }
}
</script> 
  
  
<style scoped >
.el-tree {
  border: 1px solid #f1f1f1;
  overflow: hidden;
}

.el-tree>>>.el-tree-node__content {
  padding: 5px;
  border-bottom: 1px solid #f3f0f0;
}

.el-tree>>>.el-tree-node__content .custom-tree-node {
  width: 100%;
  overflow: hidden;
  height: 30px;
  line-height: 30px;
}

.el-tree>>>.el-tree-node__content .custom-tree-node .dept-name {
  width: 500px;
  float: left;
  padding: 0 10px;
  cursor: pointer;
}

.el-tree>>>.el-tree-node__content .custom-tree-node .dept-code {
  float: left;
  padding: 0 10px;
}

.el-tree>>>.el-tree-node__content .custom-tree-node .dept-oper {
  float: right;
  width: 240px;
  text-align: left;
  padding: 0 10px;
}
</style>
  